const Net = require('../../../utils/common')
import TIM from '../../../miniprogram_npm/tim-wx-sdk/index';
import COS from '../../../miniprogram_npm/cos-wx-sdk-v5/index';
const options = {
  SDKAppID: wx.getStorageSync('member') ? wx.getStorageSync('member').live.app_id : 1400408830 // 接入时需要将0替换为您的即时通信应用的 SDKAppID
  // SDKAppID: 1400394368 // 接入时需要将0替换为您的即时通信应用的 SDKAppID
};
let tim = TIM.create(options);
tim.registerPlugin({
  'cos-wx-sdk': COS
})
Page({
  data: {
    id: '',
    info: '',
    controls: false,
    scrolltop: 0,
    list: [{
      username: '公告：欢迎来到直播间，喜赠倡导绿色直播，直播间内严禁出现违法违规行为，若有上述情况请及时举报！',
      centent: '',
      type: 3
    }],
    listss: [{
      username: '公告：欢迎来到直播间，喜赠倡导绿色直播，直播间内严禁出现违法违规行为，若有上述情况请及时举报！',
      centent: '',
      type: 3
    }],
    showInput: false,
    onUserInputValue: '',
    onShaerView: false,
    showShopViewStatua: false,
    cleraViewStatus: false,
    onComeLiveRoomList: [],
    endLiveInfo: null,
    userLoginStatus: false,
    shareUserInfo: '',
    onBannerShow: false
  },
  onLoad: function (options) {
    var _this = this
    if (options.member) {
      _this.onShareUserInfo(options.member)
    }
    Net.data({
      userLoginStatus: wx.getStorageSync('token') ? true : false
    })
    var sysinfo = wx.getSystemInfoSync(),
      statusHeight = sysinfo.statusBarHeight,
      isiOS = sysinfo.system.indexOf('iOS') > -1,
      navHeight;
    if (!isiOS) {
      navHeight = 48;
    } else {
      navHeight = 44;
    }
    Net.data({
      status: statusHeight,
      navHeight: navHeight
    })
    Net.data({
      id: options.id
    })
  },
  // 请求获取邀请人信息
  onShareUserInfo(e) {
    Net.link('v1/getRefereeInfo', {
      number: e
    }, function (res) {
      res.data.data.nickname = 'AA'
      Net.data({
        shareUserInfo: res.data.data
      })
    })
  },
  errorFcuntion(e) {
    if (e.detail.code == '-2301' || e.detail.code == '2101') {
      Net.toast('重连失败', 'none')
      setTimeout(() => {
        if(Net.data('shareUserInfo')){
          wx.switchTab({
            url: '/tabbarPage/index/index',
          })
        }else{
          wx.navigateBack({
            delta: 1
          })
        }
      }, 1000);
    }
    console.log('错误拉流', e)
  },
  onShowShopView() {
    Net.data({
      showShopViewStatua: !Net.data('showShopViewStatua')
    })
  },
  onShaerStatus() {
    // Net.toast('暂未开放', 'none')
    // return false
    Net.data({
      onShaerView: !Net.data('onShaerView')
    })
  },
  onPageInfo(e) {
    var _this = this 
    Net.link('v1/getLiveInfo', {
      live_id: Net.data('id')
    }, function (res) {
      console.log(res)
 
      // res.data.data.user_cache.member_oauth_info.nicknameStatus = true
      Net.data({
        info: res.data.data
      })
      if(res.data.data.live_info.live_status != 3&& res.data.data.live_info.live_status != 1){
        Net.link('v1/finishLive', {
          is_playback: 0,
          live_id: Net.data('id')
        }, function (res) {
          console.log(res)
          res.data.data.live_info.entLiveTime = Net.formatTime(res.data.data.live_info.end_time - res.data.data.live_info.create_time, 'm:s')
          Net.data({
            endLiveInfo: res.data.data
          })
        }, "GET", function (res) {}, 'live')
        return false
      }
      console.log(Net.data('info'))
      if (wx.getStorageSync('onHomeLive') != 'successFul') {
        _this.onReceiveInfoGroup()
      }
      let promise = tim.login({
        userID: res.data.data.user_cache ? JSON.stringify(Net.data('liveInfo').user_cache.member_oauth_info.member_id) : res.data.data.tourists_info.tourists_id,
        userSig: res.data.data.user_cache ? Net.data('liveInfo').tencent_sig : res.data.data.tourists_info.tourists_sig
      });
      promise.then(function (imResponse) {
        console.log(imResponse.data); // 登录成功
        // if (imResponse.data.repeatLogin === true) {
        console.log('>>>>>>>>>>>>>>>', Net.data('info').live_info.im_room)
        let promise = tim.joinGroup({
          groupID: Net.data('info').live_info.im_room,
          type: TIM.TYPES.GRP_AVCHATROOM
        });
        promise.then(function (imResponse) {
          console.log('群状态', imResponse);
          switch (imResponse.data.status) {
            case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意
              console.log('等待管理员同意')
              break;
            case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
              console.log(imResponse.data.group); // 加入的群组资料
              console.log('加入的群组资料')
              break;
            case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
              console.log('已在群里')
              break;
            default:
              break;
          }
          console.log('无状态')
        }).catch(function (imError) {
          console.warn('joinGroup error:', imError); // 申请加群失败的相关信息
        });
        console.log(imResponse.data.errorInfo);
        // }
      }).catch(function (imError) {
        console.warn('login error:', imError); // 登录失败的相关信息
      });
      // setTimeout(() => {
      //   var info = Net.data('info')
      //   info.user_cache.member_oauth_info.nicknameStatus = false
      //   Net.data({
      //     info: info
      //   })
      // }, 2500);
    }, 'POST', function (res) {}, 'live')
  },
  onLiveLogin() {
    console.log('登录程序启动')
    var _this = this
    Net.link('v1/loginLive', {}, function (res) {
      console.log(res)
      console.log({
        userID: JSON.stringify(res.data.data.user_cache.member_oauth_info.member_id),
        userSig: res.data.data.tencent_sig
      })
      Net.data({
        liveInfo: res.data.data
      })
    }, 'GET', function (res) {
      console.log('LoginLive失敗')
    _this.onPageInfo()
    }, 'live')
    setTimeout(() => {
      _this.onPageInfo()
    }, 2000);
  },
  // 用户登录获取
  onGetUserLogin(e) {
    console.log(e)
    var _this = this
    wx.login({
      success: res => {
        const userInfo = e.detail;
        userInfo.userInfo.nickName = 'AA'
        var string = JSON.parse(userInfo.rawData)
        string.nickName = 'AA'
        userInfo.rawData = JSON.stringify(string)

        wx.setStorageSync('Info', userInfo)
        var stringInfo = JSON.stringify(userInfo)
        console.log('传给组件的', stringInfo)
        // var info = stringInfo.split(''),
        //   list = ''
        // for (let i in info) {
        //   if (info[i] != ' ') {
        //     list = list + info[i]
        //   }
        // }
        var referee_data = _this.data.shareUserInfo
        if (referee_data) {
          var data = {
            client_data: stringInfo,
            code: res.code,
            referee_data: JSON.stringify(referee_data)
          }
        } else {
          var data = {
            client_data: stringInfo,
            code: res.code
          }
        }
        console.log('变了味道的data', data)
        _this.userLogin(data)
      }
    })
  },
  //授权登录
  userLogin(data) {
    var _this = this
    Net.link('v1/wxLogin', data,
      function (res) {
        wx.setStorageSync('token', res.data.data.token)
        if (res.data.code == 200 || res.data.code == 201) {
          wx.showToast({
            icon: 'success',
            title: '登录成功',
          })
          Net.data({
            userLoginStatus: true
          })
          _this.onLiveLogin()
        } else if (res.data.code == 402) {
          wx.login({
            success: (res) => {
              data.code = res.code
              _this.wxLogin(data)
            },
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      })
  },
  //授权登录
  wxLogin(data) {
    var _this = this
    Net.link('v1/wxRegister', data, function (res) {
      wx.setStorageSync("token", res.data.data.token)
      Net.data({
        userLoginStatus: true
      })
      wx.showToast({
        icon: 'success',
        title: '登录成功',
      })
      _this.onLiveLogin()
    })
  },
  onBack() {
    if(Net.data('shareUserInfo')){
      wx.switchTab({
        url: '/tabbarPage/index/index',
      })
    }else{
      wx.navigateBack({
        delta: 1
      })
    }
  },
  //接收消息
  onReceiveInfoGroup() {
    wx.setStorageSync('onHomeLive', 'successFul')
    console.log('开始接收消息')
    let onMessageReceived = function (event) {
      console.log(event)
      console.log('开始接收消息')
      if (event.data[0]._elements[0].content.operationType == 5) {
        Net.link('v1/finishLive', {
          is_playback: 0,
          live_id: Net.data('id')
        }, function (res) {
          console.log(res)
          res.data.data.live_info.entLiveTime = Net.formatTime(res.data.data.live_info.end_time - res.data.data.live_info.create_time, 'm:s')
          Net.data({
            endLiveInfo: res.data.data
          })
        }, "GET", function (res) {}, 'live')
      }
      if (event.data[0].payload.userDefinedField) {
        var info = JSON.parse(event.data[0].payload.userDefinedField)
        console.log(info.content.data.nickname, '进来了直播间')
        console.log(info.type, 'type值~')
        if (info.type == 1) {
          Net.data({
            onComeLiveRoomList: []
          })
          setTimeout(() => {
            let list = Net.data('onComeLiveRoomList')
            list.push({
              username: info.content.data.nickname,
              centent: info.content.data.content,
            })
            Net.data({
              onComeLiveRoomList: list
            })
            setTimeout(() => {
              Net.data({
                onComeLiveRoomList: []
              })
            }, 2000);
          }, 500);

        } else {
          let list = Net.data('list')
          list.push({
            username: info.content.data.nickname,
            centent: info.content.data.content,
          })
          Net.data({
            list: list,
            scrolltop: Number(list.length) * 500
          })
        }
      } else {
        if (event.data[0].payload.data) {
          let list = Net.data('list')
          var info = JSON.parse(event.data[0].payload.data)
          console.log(info.content.data.nickname, '发送的消息：', info.content.data.content)
          list.push({
            username: info.content.data.nickname,
            centent: info.content.data.content,
          })
          Net.data({
            list: list,
            scrolltop: Number(list.length) * 500,
          })
        } else {
          let list = Net.data('list')
          var info = JSON.parse(event.data[0].payload.text)
          console.log(info.content.data.nickname, '发送的消息：', info.content.data.content)
          list.push({
            username: info.content.data.nickname,
            centent: info.content.data.content,
          })
          Net.data({
            list: list,
            scrolltop: Number(list.length) * 500,
          })
        }

      }
    }
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
  },
  onReady: function () {},
  onShow: function () {
    var _this = this
    _this.onLiveLogin()
  },
  onHide: function () {},
  onUnload: function () {
    console.log('取消监听')
    let promises = tim.quitGroup(Net.data('info').live_info.im_room);
    promises.then(function (imResponse) {
      console.log('已退出群聊：', imResponse.data.groupID);
    }).catch(function (imError) {
      console.warn('quitGroup error:', imError);
    });
    let promise = tim.logout();
    promise.then(function (imResponse) {
      console.log(imResponse.data);
    }).catch(function (imError) {
      console.warn('logout error:', imError);
    });
    wx.removeStorageSync('_mta_auid')
    wx.removeStorageSync('_mta_ssid')
    wx.removeStorageSync('TIM_1400378574_9_profile')
    wx.removeStorageSync('_mta_ntdata')
    wx.removeStorageSync('TIM_1400378574_9_groupMap')
    wx.removeStorageSync('TIM_1400378574_9_conversationMap')
  },
  onPullDownRefresh: function () {},
  onReachBottom: function () {},
  onShareAppMessage: function () {
    Net.data({
      onShaerView: !Net.data('onShaerView')
    })
    return {
      title: Net.data('info').live_info.nickname + '的直播间，快来围观！',
      path: '/pages/onNewPages/onLiveInfopage/onLiveInfopage?id=' + Net.data('info').live_info.live_id + '&member=' + Net.data('liveInfo').user_cache.number,
      imageUrl: Net.data('info').live_info.front_cover
    }
  },
  onBingInput(e) {
    Net.data({
      onUserInputValue: e.detail.value
    })
  },
  onContctBut(e) {
    console.log(e)
    var _this = this,
      list = _this.data.list
    if (!_this.data.onUserInputValue || e.type == "confirm" ? !e.detail.value : !_this.data.onUserInputValue) {
      wx.showToast({
        title: '请输入内容在发送',
        icon: 'none'
      })
    } else {
      var data = JSON.stringify({
        content: {
          data: {
            content: e.type == "confirm" ? e.detail.value : _this.data.onUserInputValue,
            nickname: Net.data('info').user_cache.member_oauth_info.nickname
          }
        },
        type: -1
      })
      let message = tim.createTextMessage({
        to: Net.data('info').live_info.im_room,
        conversationType: 'GROUP',
        payload: {
          text: data
        }
      });
      // 2. 发送消息
      let promise = tim.sendMessage(message);
      promise.then(function (imResponse) {
        console.log(imResponse);
      }).catch(function (imError) {
        console.warn('sendMessage error:', imError);
      });
      list.push({
        username: _this.data.info.user_cache.member_oauth_info.nickname,
        centent: e.type == "confirm" ? e.detail.value : _this.data.onUserInputValue
      })
      Net.data({
        list: list,
        scrolltop: Number(list.length) * 500,
        showInput: false,
        onUserInputValue: ''
      })
    }
  },
  onHidInput() {
    var _this = this
    Net.data({
      showInput: false,
      onUserInputValue: ''
    })
  },
  onUserSpick() {
    Net.data({
      showInput: true
    })
  },
  onLiveTap() {
    Net.data({
      cleraViewStatus: !Net.data('cleraViewStatus'),
      showShopViewStatua: false,
      onShaerView: false
    })
  },
  onFollowClick(e) {
    Net.link('v1/liveLike', {
      type: e.currentTarget.id,
      host_id: Net.data('info').live_info.member_id,
      live_id: Net.data('id')
    }, function (res) {
      console.log(res)
      var info = Net.data('info')
      info.live_info.follow_status = e.currentTarget.id
      Net.data({
        info: info
      })
      Net.toast('关注成功', 'success')
    }, "POST", function (res) {}, 'live')
  },
  onShareButn(e) {
    if (e.currentTarget.id == 2) {
      Net.data({
        onBannerShow: !Net.data('onBannerShow'),
        onSpickerGoods: ''
      })
      return false
    }
    if (e.currentTarget.id == 3) {
      wx.getImageInfo({
        src: Net.data('onSpickerGoods'),
        success(res) {
          wx.saveImageToPhotosAlbum({
            filePath: res.path,
            success(res) {
              wx.showToast({
                icon: 'success',
                title: '保存成功',
              })
              Net.data({
                onBannerShow: false,
                onSpickerGoods: ''
              })
            }
          })
        }
      })
      return false
    }
    if (e.currentTarget.id == 1) {
      Net.link('v1/poster', {
        live_id: Net.data('id'),
        goods_url: 'http://img.alicdn.com/imgextra/i1/890482188/O1CN018n0R6x1S29CBPah6U_!!890482188-0-lubanu-s.jpg_60x60q90.jpg'
      }, function (res) {
        Net.data({
          onSpickerGoods: res.data.data.poster_path,
          onBannerShow: true,
          onShaerView:false
        })
      }, "POST", function (res) {}, 'live')
      return false
    }


  }
})